<template>
  <div id="tool-wrapper" :style="{ right: isManage ? '1%' : '30%' }">
    <div
      class="tool-item"
      v-for="item in tools"
      :title="item.title"
      @click="handleClick(item)"
    >
      <a-popover
        v-if="item.title === '图层控制'"
        placement="leftTop"
        trigger="click"
        overlayClassName="custom-popover"
      >
        <template #content>
          <LineContorller></LineContorller>
        </template>
        <i :class="['iconfont', item.icon, disabled ? 'disabled-icon' : '']">
        </i>
      </a-popover>
      <i :class="['iconfont', item.icon]" v-else></i>
    </div>
  </div>
</template>

<script setup>
import toolList from './toolList'
import { ref, onMounted, watch,computed } from 'vue'
import { watchLineData, useLineData } from '@/store'
import LineContorller from './LineContorller.vue'
import { renderAll, renderStation } from '@/cesiumTools/effectController'
import PositionStatusBar from '@/cesiumTools/PositionStatusBar.js'
// import { fullScreen, cancelFullScreen } from './toolFunctions'
import { useRoute } from 'vue-router'


const route = useRoute()

const tools = ref(toolList)
const lineDataStore = useLineData()
const disabled = ref(false)
const isManage = ref(false)
const isFullScreen = ref(false)
const MousePositionShowed = ref(false)
let positionStatusBarInstance = ref();  // 用于检查鼠标位置是否创建

// 监听viewer是否设置，如果设置了可以获取viewer
// const promise = watchLineData('setViewer')
// promise.then((viewer) => {
//   console.log('已获取viewer：', viewer)
// })

// 监听路由变化
watch(
  () => route.path, // 监听路由路径
  (newPath) => {
    // 根据路由路径设置 disabled 值
    disabled.value = newPath === '/progress-history'
  },
  { immediate: true } // 在组件挂载时立即执行一次
)

onMounted(async() => {
  const viewer = await watchLineData('setViewer')
  const lineData = await watchLineData('setData')
  console.log('已获取viewer：', viewer)
  console.log('已获取lineData：', lineData)
  renderAll(viewer, lineData)
})

// const promise=watchLineData('setViewer')
// promise.then(viewer=>{
// 	  console.log(viewer);
// })

/* ========================全屏控件====================== */
const fullScreen = (element) => {  
  // 检查是否支持全屏，并且全屏模式未禁用  
  if (!document.fullscreenEnabled && !document.mozFullScreenEnabled) {  
    return Promise.reject(new Error("全屏模式被禁用或不支持"));  
  }  
  let result = null;  
  // 尝试请求全屏  
  if (element.requestFullscreen) {  
    result = element.requestFullscreen();  
  } else if (element.mozRequestFullScreen) { // Firefox  
    result = element.mozRequestFullScreen();  
  } else if (element.msRequestFullscreen) { // IE/Edge  
    result = element.msRequestFullscreen();  
  } else if (element.webkitRequestFullscreen) { // Chrome, Safari 和 Opera  
    result = element.webkitRequestFullscreen();  
  }  
  // 返回结果或 reject  
  return result ? Promise.resolve(result) : Promise.reject(new Error("不支持请求全屏模式"));  
};

const cancelFullScreen = () => {  
  if (document.exitFullscreen) {  
    return document.exitFullscreen();  
  } else if (document.mozCancelFullScreen) { // Firefox  
    return document.mozCancelFullScreen();  
  } else if (document.msExitFullscreen) { // IE/Edge  
    return document.msExitFullscreen();  
  } else if (document.webkitExitFullscreen) { // Chrome, Safari 和 Opera  
    return document.webkitExitFullscreen();  
  }  
  return Promise.reject(new Error("不支持退出全屏模式"));  
};  

// 全选，控制所有站点，站线
const controlAll = (e) => {
  const checked = e.target.checked;
  const lineNames = lineData.value.map((item) => item.name);
  const stationNames = [];
  lineData.value.forEach((item) => {
    const { stationsList } = item;
    stationsList.forEach((station) => {
      stationNames.push(station.name);
    });
  });
  // 控制地图元素显示隐藏
  displayByName(lineNames, stationNames, checked);
  // 控制ui面板显示隐藏
  lineData.value = lineData.value.map((item) => {
    item.checked = checked;
    return item;
  });
};

// 单独控制站线
const chooseLine = (item) => {
  const names = [item.name];
  const stationNames = item.stationsList.map((station) => station.name);
  // 控制ui面板显示隐藏
  item.checked = !item.checked;
  // 控制地图元素显示隐藏
  displayByName(names, stationNames, item.checked);
  // console.log(item.checked, "item.checked")
  // console.log(item, "item.checked")
  // console.log(stationNames, "stationNames")
};

//2.全选和反选
const isAllSelected = computed({
  get() {
    return lineData.value.every((item) => item.checked);
  },
  set(val) {
    lineData.value.forEach((item) => (item.checked = val));
  },
});
lineDataStore.$onAction(({ name, store, args, after, onError })=>{
  if (name === 'disableController'){
    after((res) => {
        disabled.value = lineDataStore.isDisable;
    });
  }
})
const handleClick = (item) => {
  console.log('Clicked item:', item)
  // 全屏控件
  if (item.title === '全屏') {
    isFullScreen.value = !isFullScreen.value
    console.log(isFullScreen.value)
    const content = document.getElementById('app')
    console.log(content)
    if (isFullScreen.value) {
      fullScreen(content)
        .then(() => {
          console.log('已进入全屏模式')
        })
        .catch((error) => {
          console.error('进入全屏模式失败:', error)
        })
    } else {
      cancelFullScreen()
        .then(() => {
          console.log('已退出全屏模式')
        })
        .catch((error) => {
          console.error('退出全屏模式失败:', error)
        })
    }
  }
  
  // 鼠标位置
  if (item.title === '鼠标位置') {
    MousePositionShowed.value = !MousePositionShowed.value;
    if (MousePositionShowed.value) {
      positionStatusBarInstance.value = new PositionStatusBar(lineDataStore.viewer);
      console.log('PositionStatusBar已创建');
    } else {
      if (positionStatusBarInstance.value) {
        positionStatusBarInstance.value.destroy();
        positionStatusBarInstance.value = null; // 清空引用
      }
      console.log('PositionStatusBar已销毁');
    }
  }
  // 图层控制
  // if (item.title === '图层控制') {
  //   isManage.value = !isManage.value
  //   if (isManage.value) {
  //     tools.value = [
  //       {
  //         title: '图层控制',
  //         icon: 'icon-layer',
  //         component: LineContorller
  //       }
  //     ]
  //   } else {
  //     tools.value = toolList
  //   }
  // }
}






















</script>
<style scoped>
#tool-wrapper {
  position: absolute;
  left: 70%;
  bottom: 10%;
  display: flex;
  flex-direction: column;
  z-index: 199;
}

.tool-item {
  margin: 4px;
  pointer-events: all;
  cursor: pointer;
}

.tool-item:hover {
  background-color: #d8951a7f;
}

#tool-wrapper i {
  color: #ffd31a;
  border: 1px solid #d8951a;
  padding: 3px;
}

#tool-wrapper span {
  color: #fff;
}

.disabled-icon {
  pointer-events: none;
  cursor: none;
  background-color: rgba(204, 204, 204, 0.306);
}

.disabled-icon:hover {
  cursor: none;
}
</style>
